<template>
  <el-upload
    ref="upload"
    v-model:file-list="fileList"
    class="upload-comp leading-[20px] w-[100%]"
    action="#"
    :limit="limit"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :http-request="handleHttpRequest"
    v-bind="$attrs"
  >
    <div class="flex flex-1 items-center justify-between">
      <div class="flex items-center">
        <span
          class="text-[14px] text-[var(--el-text-color-regular)] leading-[22px] font-[700]"
        >
          {{ label }}<span class="text-[#E50113]" v-if="require">*</span>
        </span>
        <el-divider direction="vertical" />
        <div class="pointer-cursor text-[14px] text-[#333]">
          <span class="iconfont icon-upload mr-[4px]"></span>
          <span>上传附件</span>
        </div>
      </div>
      <div>
        <slot name="headRight"></slot>
      </div>
    </div>
    <template #file="{ file }">
      <span>{{ file.name }}</span>
      <span class="text-[#3487FF] cursor-pointer">
        <span class="mx-[8px]" v-if="file.url">下载</span>
        <span class="text-[#E50113] ml-[8px] iconfont icon-del" @click="handleDelete(file)">
        </span>
      </span>
    </template>
    <template #tip v-if="!fileList.length">
      <div class="el-upload__tip text-[#ccc] text-[14px] leading-[20px]">
        尚未添加附件
      </div>
    </template>
  </el-upload>
</template>

<script setup>
import { genFileId, ElMessage } from 'element-plus'
const props = defineProps({
  label: { type: String, default: '附件' },
  require: { type: Boolean, default: false },
  limit: { type: Number, default: 1 },
  modelValue: { type: Array, default: () => [] },
})

const emit = defineEmits(['update:modelValue'])

import { uploadFile } from '@/api/public.js'

const upload = ref()
const fileList = ref([])

watch(
  () => props.modelValue,
  val => {
    fileList.value = val
  }
)

watch(
  () => fileList.value,
  val => {
    emit('update:modelValue', val.length ? val : undefined)
  },
  {
    immediate: true,
    deep: true,
  }
)

const beforeUpload = file => {
  const limitSize = 500
  const isLt500M = file.size / 1024 / 1024 < limitSize
  if (!isLt500M) {
    ElMessage.error(`上传文件大小不能超过 ${limitSize}MB!`)
  }
  return isLt500M
}

const handleHttpRequest = async options => {
  let formData = new FormData()
  const { file } = options
  formData.append('file', file)
  try {
    const { data } = await uploadFile(formData, 'f')
    return data
  } catch (e) {
    console.error(e)
    options.onError(e)
  }
}

const handleExceed = files => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
  upload.value.submit()
}

const handleSuccess = (_res, _file, _fileList) => {
  processFileList(_fileList)
}

const processFileList = _fileList => {
  const _data = _fileList.map(item => {
    if (!item.filepath && item.response) {
      const response = item.response
      return { ...item, ...response }
    }
    return item
  })
  fileList.value = _data
}

const handleDelete = e => {
  const _data = fileList.value
  const _index = _data.find(n => n.uid === e.uid)
  fileList.value.splice(_index, 1)
}

const clearFiles = ()=> {
    upload.value.clearFiles()
}
defineExpose({ clearFiles });
</script>
<style lang="scss" scoped>
.upload-comp {
  :deep(.el-upload) {
    line-height: 20px;
    width: 100%;
  }
}
</style>
